import axios from 'axios';
import { showFailToast } from 'vant';
import useStore from '@/store/index';
import Router from '@/router/index';
import userInfo from "@/store/modules/userInfo.js";

const baseURL = "http://localhost:8081";
const request = axios.create({
	timeout: 5000,
	baseURL
});

// 请求拦截器
request.interceptors.request.use(config => {
	const { userInfo } = useStore()
	// 1. 获取用户信息对象
	const token = userInfo.getToken;
	// // 2. 判断是否有token
	if (token) {
		// 3. 设置token
		config.headers.Authorization = `${token}`;
	}
	return config;
}, err => {
	return Promise.reject(err);
});

// 响应拦截器
request.interceptors.response.use(response => {
	const { userInfo } = useStore()
	if (response.data.code !== 200) {
		if (response.data.code == 1011) {
			showFailToast("登录失效,请重新登录");
			Router.push("/mine")
			userInfo.logout()
			return Promise.reject(response.data.message);
		}
		showFailToast(response.data.message);
		return Promise.reject(response.data.message);
	}
	return response.data
}, err => {
	return Promise.reject(err);
});

// 请求工具函数
export default (url, method, submitData) => {
	return request({
		url,
		method,
		[method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
	});
};
